//
//  ForgotVC.swift
//  YueChat
//
//  Created by IMac on 2024/9/12.
//

import UIKit

class ForgotVC: BaseVC {

    private var times: Int = 0
    var timer: Timer?
    @IBOutlet weak var loginBtn: UIButton! //验证码登录
    @IBOutlet weak var accView: UIView!
    @IBOutlet weak var pwdView: UIView!
    
    @IBOutlet weak var pwd2View: UIView!
    @IBOutlet weak var codeView: UIView!
    @IBOutlet weak var loginSendCodeBtn: UIButton! //获取验证码
    
    @IBOutlet weak var accountTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var registerConfirmTextField: UITextField!
    @IBOutlet weak var registerCodeTextField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        
        accView.layer.cornerRadius = 10
        accView.layer.borderWidth = 1
        accView.layer.borderColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1).cgColor
        
        pwdView.layer.cornerRadius = 10
        pwdView.layer.borderWidth = 1
        pwdView.layer.borderColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1).cgColor
        pwd2View.layer.cornerRadius = 10
        pwd2View.layer.borderWidth = 1
        pwd2View.layer.borderColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1).cgColor
        codeView.layer.cornerRadius = 10
        codeView.layer.borderWidth = 1
        codeView.layer.borderColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1).cgColor
        
        loginBtn.layer.cornerRadius = 10
        loginSendCodeBtn.layer.cornerRadius = 10
        
        if let account = UserDefaults.standard.string(forKey: "mhhy_account") {
            self.accountTextField.text = account
            self.accountTextField.isUserInteractionEnabled = false
        }
    }

    @IBAction func back(_ sender: Any) {
        dismiss(animated: true)
    }
    
    // 找回密码 发送验证码
    @IBAction func getCode(_ sender: Any) {//获取验证码
        guard let accountText = accountTextField.text, !accountText.isEmpty else {
            MHAlert.showMessage("InputAccnout".localized())
            return
        }

        guard isValidPhoneNumber(phoneNumber: accountText) else {
            MHAlert.showMessage( "AccountError".localized())
            return
        }

        SVProgressHUD.show()
        Task {
            let (res, err) = await gosnLogin.getCode(accountText,3)
            await MainActor.run {
                SVProgressHUD.dismiss()
                if err == nil {
                    MHAlert.showMessage(KLocalizedString("CodeSendSuccess"))
                    self.changeSendCodeStatus()
                }else{
                    MHAlert.showMessage("\(err!.description)")
                }
            }
        }
        

//        let url = "https://abc.tjlm.top:19314/user-service/api/user/send-code"
//
//        var parameters: [String: Any] = [:]
//
//        parameters = ["type": 3, "target": accountText]
//
//        SVProgressHUD.show()
//        
//        MHHYHttpTool.post(url, params: parameters) { [self] task, response in
//            defer {
//                
//            }
//            guard let data = response as? Data else { return }
//            guard let dict = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { return }
//            SVProgressHUD.dismiss()
//            if self.invitedCode((dict["code"] as! NSNumber)) {
//                DispatchQueue.main.async {
//                    MHAlert.showMessage(KLocalizedString("CodeSendSuccess"))
//                    self.changeSendCodeStatus()
//                }
//                
//            } else {
//                let errMessage = dict["msg"] as? String ?? "LoginError".localized()
//                MHAlert.showMessage(errMessage)
//            }
//        } fail: { _, error in
//            MHAlert.showMessage("NetWorkingError".localized())
//        }
    }
    
    func changeSendCodeStatus() {
        times = 60
        loginSendCodeBtn!.endEditing(false)
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
//        Timer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
    }
    
    @objc func timerAction() {
        times -= 1
        loginSendCodeBtn!.setTitle("(\(times)s)", for: .normal)
        
        if times <= 0 {
            timer?.invalidate()
            timer = nil
            loginSendCodeBtn.setTitle(NSLocalizedString("SendCodeBtnText", comment: ""), for: .normal)
            loginSendCodeBtn.isEnabled = true
        }
    }

    // 假设 registerNewUser 是一个按钮点击事件的处理函数
    @IBAction func register(_ sender: Any) {
        guard let accountText = accountTextField.text, !accountText.isEmpty else {
            MHAlert.showMessage(KLocalizedString("InputAccnout"))
            return
        }
        
        if !isValidPhoneNumber(phoneNumber: accountText) {
            MHAlert.showMessage(KLocalizedString("AccountError"))
            return
        }
        
        guard let passwordText = passwordTextField.text, !passwordText.isEmpty else {
            MHAlert.showMessage(KLocalizedString("InputSetingPwd"))
            return
        }
        
        if registerConfirmTextField.text != passwordText {
            MHAlert.showMessage(KLocalizedString("InputConfirmPwd"))
            return
        }
        
        guard let codeText = registerCodeTextField.text, !codeText.isEmpty else {
            MHAlert.showMessage(KLocalizedString("InputCode"))
            return
        }
        
        SVProgressHUD.show()
        Task {
            let (res, err) = await ghttpService.forgotPassword(accountText, passwordText, codeText)
            await MainActor.run {
                SVProgressHUD.dismiss()
                if let err = err {
                    MHAlert.showMessage("\(err.description)")
                }else{
                    MHAlert.showMessage(KLocalizedString("ChangePswSuccess"))
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        self.dismiss(animated: true)
                    }
                }
            }
        }
        
//        // 找回密码
//        let url = "https://abc.tjlm.top:19314/user-service/api/user/change-password-by-code"
//        MHHYHttpTool.setJsonRequest()
//        
//        let hashedPassword = EcUtils.osnHash(data:passwordText.data(using: .utf8)!)
//        
//        let dic: [String: Any] = [
//            "target": accountText,
//            "newPassword": hashedPassword as Any,
//            "code": codeText
//        ]
//        
//        SVProgressHUD.show()
//        
//        MHHYHttpTool.post(url, params: dic) { (data, response) in
//            defer {
//                
//            }
//            
//            SVProgressHUD.dismiss()
//            guard let data = response as? Data else { return }
//            guard let dict = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { return }
//            
//            if self.invitedCode((dict["code"] as! NSNumber)) {
//                MHAlert.showMessage(KLocalizedString("ChangePswSuccess"))
//                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
//                    self.dismiss(animated: true)
//                }
//            } else {
//                let errMessage = dict["msg"] as? String ?? KLocalizedString("ChangePswError")
//                MHAlert.showMessage(errMessage)
//            }
//        } fail: { (task, error) in
//            MHAlert.showMessage(KLocalizedString("NetWorkingError"))
//        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
}
